<div
  x-ref="searchBarRef"
  x-data="{ open: false }"
  @click.outside="open = false;"
  @keyup.escape.window="open = false"
  id="search-bar"
  class="relative flex w-full max-w-full items-center overflow-visible"
>
  <input
    class="min-w-0 border-none outline-none focus:outline-none"
    x-ref="searchBarInput"
    type="search"
    id="search-bar-input"
    placeholder="Search"
    @focus="open = true;"
    @keyup.enter.prevent="window.location.href = '/search/?q=' + $event.target.value;"
    @keyup.escape.prevent="open = false;"
    @keydown.window="(e) => {
            switch(e.key) {
            case 'k':
              if (e.metaKey || e.ctrlKey) {
                e.preventDefault();
                $el.focus();
              }
              break;
            }
          }"
    tabindex="0"
  />
  <button
    id="search-bar-icon"
    @click="window.location.href = '/search/?q=' + $refs.searchBarInput.value;"
    class="cursor-pointer transition-opacity hover:opacity-80"
    aria-label="Search"
  >
    <span class="icon-svg-stroke">
      {{ partial "utils/svg.html" "/icons/search.svg" }}
    </span>
  </button>
  <div
    id="search-bar-dropdown"
    x-show="open"
    x-cloak
    x-ref="dropdown"
    class="border-1 fixed z-[999] mt-2 hidden rounded-sm border-gray-100 bg-gray-50 p-6 font-medium text-gray-400 shadow-md md:block dark:border-gray-700 dark:bg-gray-900 dark:text-gray-200"
    style="width: min(500px, 90vw)"
    x-effect="if (open) {
        const rect = $refs.searchBarRef.getBoundingClientRect();
        const dropdownWidth = Math.min(500, window.innerWidth * 0.9);
        const viewportWidth = window.innerWidth;
        
        // Calculate left position
        let leftPos = rect.left;
        
        // Prevent going off right edge
        if (leftPos + dropdownWidth > viewportWidth - 20) {
          leftPos = viewportWidth - dropdownWidth - 20;
        }
        
        // Prevent going off left edge
        if (leftPos < 20) {
          leftPos = 20;
        }
        
        $el.style.top = (rect.bottom + 8) + 'px';
        $el.style.left = leftPos + 'px';
      }"
  >
    <div id="search-bar-results">
      {{- $emptyState := `
      <div>
        Start typing to search or try
        <button onclick="askAI('search-bar-input')" class="link">Ask AI</button
        >.
      </div>
      ` }} {{- $emptyState | safe.HTML }}
      <!-- results -->
    </div>
  </div>
  <script type="module">
    window.addEventListener("load", async function () {
      const pagefind = await import("/pagefind/pagefind.js");
      await pagefind.options({
        ranking: {
          termFrequency: 0.2,
          pageLength: 0.75,
          termSaturation: 1.4,
          termSimilarity: 6.0,
        },
      });

      const searchBarInput = document.querySelector("#search-bar-input");
      const searchBarResults = document.querySelector("#search-bar-results");
      const searchDropdown = document.querySelector("#search-bar-dropdown");

      // Update position on scroll and resize
      function updateDropdownPosition() {
        const searchBar = document.querySelector("#search-bar");
        if (
          !searchBar ||
          !searchDropdown ||
          searchDropdown.style.display === "none"
        )
          return;

        const rect = searchBar.getBoundingClientRect();
        const dropdownWidth = Math.min(500, window.innerWidth * 0.9);
        const viewportWidth = window.innerWidth;

        let leftPos = rect.left;

        if (leftPos + dropdownWidth > viewportWidth - 20) {
          leftPos = viewportWidth - dropdownWidth - 20;
        }

        if (leftPos < 20) {
          leftPos = 20;
        }

        searchDropdown.style.top = rect.bottom + 8 + "px";
        searchDropdown.style.left = leftPos + "px";
      }

      window.addEventListener("scroll", updateDropdownPosition);
      window.addEventListener("resize", updateDropdownPosition);

      async function search(e) {
        const query = e.target.value;
        if (query === "") {
          searchBarResults.innerHTML = `{{ $emptyState | safe.HTML }}`;
          return;
        }
        const search = await pagefind.debouncedSearch(query);
        if (search === null) {
          return;
        } else {
          const resultsLength = search.results.length;
          const resultsData = await Promise.all(
            search.results.slice(0, 5).map((r) => r.data()),
          );
          const results = resultsData.map((item, index) => ({
            ...item,
            index: index + 1,
          }));

          if (query) {
            searchBarResults.classList.remove("hidden");
          } else {
            searchBarResults.classList.add("hidden");
          }

let resultsHTML = `<div class="p-2 text-gray-400 dark:text-gray-500">${resultsLength} results</div>`;
resultsHTML += results
  .map((item) => {
    // Truncate excerpt if it's too long
    let excerpt = item.excerpt;
    if (excerpt.length > 200) {
      excerpt = excerpt.substring(0, 200);
    }
    return `<div class="p-2">
<div class="flex flex-col items-start item">
  <a class="link" style="word-break: break-word; overflow-wrap: anywhere;" href="${item.url}" data-query="${query}" data-index="${item.index}">${item.meta.title}</a>
  <p class="text-black dark:text-white overflow-hidden text-left" style="word-break: break-word; overflow-wrap: anywhere;">…${excerpt}…</p>
</div>
</div>`;
  })
  .join("");

if (resultsLength > 5) {
  resultsHTML += `<div class="w-fit ml-auto px-4 py-2"><a href="/search/?q=${query}" class="link">Show all results</a></div>`;
}

          searchBarResults.innerHTML = resultsHTML;
        }
      }

      searchBarInput.addEventListener("input", search);

      // Event delegation for tracking link clicks
      if (window.heap !== undefined) {
        searchBarResults.addEventListener("click", function (event) {
          if (event.target.tagName === "A" && event.target.closest(".link")) {
            const searchQuery = event.target.getAttribute("data-query");
            const resultIndex = event.target.getAttribute("data-index");
            const url = new URL(event.target.href);
            const properties = {
              docs_search_target_path: url.pathname,
              docs_search_target_title: event.target.textContent,
              docs_search_query_text: searchQuery,
              docs_search_target_index: resultIndex,
              docs_search_source_path: window.location.pathname,
              docs_search_source_title: document.title,
            };
            heap.track("Docs - Search - Click - Result Link", properties);
          }
        });
      }
    });
  </script>
</div>
